//
//  InputViewController.m
//  AudioKitOC
//
//  Created by Hwang on 2018/5/8.
//  Copyright © 2018年 AudioKit. All rights reserved.
//

#import "EchoController.h"
#import <AVFoundation/AVFoundation.h>

@interface EchoController ()

@property (nonatomic, strong) AVAudioUnitDelay *delay;
@property (nonatomic, strong) AVAudioEngine *engine;
@property (nonatomic, strong) NSURL *outputURL;

@end

@implementation EchoController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    _engine = [[AVAudioEngine alloc] init];
    _engine.mainMixerNode.volume = 1.0;
    _engine.inputNode.volume = 1.0;
    _delay = [[AVAudioUnitDelay alloc] init];
    //多久播放回声
    _delay.delayTime = 0.1;
    //数值越大回音次数越多
    _delay.feedback = 20;
    //高于设置数值的频率将不会产生效果
    _delay.lowPassCutoff = 500;
    [_engine attachNode:_delay];
    [_engine connect:_engine.inputNode to:_delay format:[_engine.inputNode inputFormatForBus:0]];
    [_engine connect:_delay to:_engine.mainMixerNode format:[_engine.inputNode inputFormatForBus:0]];
    [_engine connect:_engine.mainMixerNode to:_engine.outputNode format:[_engine.inputNode inputFormatForBus:0]];
    [_engine startAndReturnError:nil];
    
    
    //监听混合节点，并且导出混合音频
    NSError *error;
    if (!self.outputURL) self.outputURL = [NSURL URLWithString:[NSTemporaryDirectory() stringByAppendingString:@"echoOutput.caf"]];
    
    AVAudioMixerNode *mainMixer = [self.engine mainMixerNode];
    AVAudioFile *mixerOutputFile = [[AVAudioFile alloc] initForWriting:self.outputURL settings:[[mainMixer outputFormatForBus:0] settings] error:&error];
    NSLog(@"%@", self.outputURL);
    NSAssert(mixerOutputFile != nil, @"mixerOutputFile is nil, %@", [error localizedDescription]);
    [self.engine.mainMixerNode installTapOnBus:0 bufferSize:4096 format:[mainMixer outputFormatForBus:0] block:^(AVAudioPCMBuffer * _Nonnull buffer, AVAudioTime * _Nonnull when) {
        NSError *error;
        BOOL success = NO;
        success = [mixerOutputFile writeFromBuffer:buffer error:&error];
        NSAssert(success, @"error writing buffer data to file, %@", [error localizedDescription]);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
